<template>
  <div>
    <FilterTable
      ref="table"
      columnsRef="partPartOtherPartObliQueryIndex"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'rows'"
      :isSelectColumn="false"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="rowSelectChange"
    >
      <!-- <template slot="moreActions">
        <span @click="removeRecordHandle">删除数据</span>
      </template>
      <template slot="controls">
        <el-button size="small" type="primary" :disabled="btn0" icon="el-icon-plus" @click="toAddBtn">新建</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" :disabled="btn" @click="addHandle">新增</el-button>
        <el-button size="small" :disabled="btn1" @click="hold()">预留</el-button>
        <el-button size="small" :disabled="btn2" @click="close()">解预留</el-button>
        <el-button size="small" @click="reset">取消</el-button>
      </template> -->
    </FilterTable>
    <!-- <div style="text-align:center">

    </div> -->
    <!-- <BaseDialog :visible.sync="visible" :title="dialogTitle" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <BrandModal :ptype="ptype" :type="handleType" :rowData="formData" :obligatedNo="this.obligatedNo" @close="closeHandler" @getData="getData" />
    </BaseDialog> -->
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { queryPartObligatedItem, performExecute, performExecutes, querys, queryAllPartObligated } from '@/api/part/partOther/partObli';
import { queryAllPartObligatedItem } from '@/api/part/partOther/partObliQuery';
// import BrandModal from './tabs/brandModal';
import { searchStroageList } from '@/api/part/partOther/partWaterBook';
// import add from './tabs/add';
import { log } from 'util';
import { getUserId } from '@/assets/js/auth';
import { getAllUser } from '@/api/customerRepair/afterSaleVisit/resultEntry';
import { findStorageCode } from '@/api/common/auth/roleManage/index.js';
import { arrayObjDeWeight, confirmAction } from '@/utils';
import { isAuthorized } from '@/utils/index';
// import { confirmAction, notifyAction } from '@/utils';
export default {
  name: 'Brand',
  components: {},
  mixins: [dictionary],
  data() {
    this.conf = { add: '确定', edit: '编辑', show: '显示' };
    this.BaseTable = null;
    this.tableData = [];
    return {
      chooseFlag: 0,
      selectColumns: [],
      fetchApi: queryAllPartObligatedItem,
      fetchParams: {},
      dataSource: [],
      userList: [], // 人员信息表
      visible: false,
      formDatagongdan: '',
      visible1: false,
      handleTypegongdan: '',
      dialogTitle: '',
      dialogTitle1: '',
      columns: this.createTableColumns(),
      handleType: '',
      handleType1: '',
      formData: {},
      formData1: {},
      arr: {},
      visiblegongdan: false,
      dialogTitlegongdan: '',
      yuliudan: false,
      btn: true,
      btn0: false,
      btn1: true,
      btn2: true,
      btnDisabled: false,
      itemIds: '',
      codeName: [],
      userId: '',
      obligatedNo: null,
      partFlag: false, // 预约数量
      setPerformExecuteFlag: false
    };
  },
  props: { LfetchParams: {} },
  computed: {},
  watch: {
    LfetchParams: {
      handler(newVal, oldVal) {
        console.log('LPnv', newVal);
        this.changeHandle(newVal);
      }
    },
    setPerformExecuteFlag() {
      this.getAll();
    }
  },
  mounted() {
    this.initSelect();
    this.getCode();
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    this.flag3 = true;
  },

  methods: {
    exportFun(row) {
      for (const key in row) {
        switch (key) {
          case 'applicant':
            if (row[key]) {
              row[key] = this.userList[row[key]];
            }
            break;
          case 'isObligated':
            if (row[key]) {
              row[key] = this.createDictText(row[key], '1004');
            }
            break;
          case 'storageName':
            if (row['storageCode']) {
              row[key] = this.getStorageName(row['storageCode']);
            }
            break;
          default:
            break;
        }
      }
    },
    // 删除操作

    async initSelect() {
      let res = await getAllUser();
      // 去重
      let dataList = arrayObjDeWeight(res.data, 'userId');
      res.data.map(e => {
        this.userList[e.userId] = e.employeeName;
      });

      // this.topFilterList.find(item => item.fieldName === 'applicant').itemList = dataList.map(x => ({ text: x.employeeName, value: x.userId }));
    },
    getAddData(x, y) {
      // this.visible1 = false;  添加页面的弹窗false关闭
      const flag = this.dataSource.find(item => {
        const isHave = item['partNo'] === y['partNo'];
        const isRuZhang = item['storageCode'] == y['storageCode'];
        return isHave && isRuZhang;
      });
      console.log(flag);
      if (flag) {
        this.$notify({
          title: '警告',
          message: '配件已存在',
          type: 'warning'
        });
        return;
      }
      this.$notify.success({ title: '提示信息', message: '添加成功!' });
      this.btn0 = this.btn2 = true;
      this.btn1 = false;
      this.BaseTable.EXECUTE_INSERT([y]);
      this.chooseFlag = 1;
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 90,
          sorter: true,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          }
        },
        // {
        //   title: '操作',
        //   dataIndex: 'column-action',
        //   width: 60,
        //   fixed: 'left',
        //   render: props => {
        //     return (
        //       <div>
        //         <el-button size="mini" type="text" disabled={this.btnDisabled} onClick={() => this.delete(props.row)}>
        //           删除
        //         </el-button>
        //       </div>
        //     );
        //   }
        // },

        {
          title: '预留单号',
          dataIndex: 'obligatedNo',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '关联单号',
          dataIndex: 'sheetNo',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '仓库',
          dataIndex: 'storageCode',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{this.getStorageName(props.row.storageCode)}</span>;
          },
          showOverflowTooltip: true
        },
        {
          title: '库位',
          dataIndex: 'storagePositionCode',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '是否预留',
          dataIndex: 'isObligated',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          render: props => {
            return <span>{this.createDictText(props.row.isObligated, '1004')}</span>;
          }
        },
        {
          title: '预留人',
          dataIndex: 'obligatedOperator',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{this.userList[props.row.applicant]}</span>;
          }
        },
        {
          title: '预留日期',
          dataIndex: 'bookingDate',
          filterType: 'date-range',
          width: 150,
          dateFormat: 'yyyy-MM-dd',
          sorter: true,
          filter: true,
          filterType: 'date-range',
          exportFormat: {
            t: 'd'
          }
        },
        {
          title: '预留数量',
          dataIndex: 'quantity',
          // disabled: false,
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'number'
        }
      ];
    },
    async getCode() {
      this.userId = await getUserId();
      let res = (await findStorageCode()).data.map(x => ({ text: x.STORAGE_NAME, value: x.STORAGE_CODE }));
      this.codeName = res;
    },
    rowSelectChange(rows) {
      // if (!rows.length) return;
      this.selectColumns = rows[0];
      console.log(this.selectColumns);
    },
    changeQuantity(val1, val2) {
      console.log(val1, 'val1');
      console.log(val2, 'val2');
      console.log(val1[Object.keys(val1)[0]], '修改后对应的编码');
      let value = val1[Object.keys(val1)[0]];
      if (value < 0.01) {
        this.partFlag = true;
      } else {
        this.partFlag = false;
      }
      if (val2.isObligated == 10041001) {
        this.btn1 = false;
      }
      if (Number(val2.useableStock) < Number(val2.quantity)) {
        return this.$notify.warning({ title: '提示信息', message: '预留数量不能大于可用库存！' });
      }
    },

    // changeQuantity(a, val) {
    //   if (val.isObligated == 10041001) {
    //     this.btn1 = false;
    //   }
    //   if (Number(val.useableStock) < Number(val.quantity)) {
    //     return this.$notify.warning({ title: '提示信息', message: '出库数量不能大于可用库存！' });
    //   }
    // },
    getStorageName(storageCode) {
      const item = this.codeName.find(x => {
        return x.value == storageCode;
      });
      return item ? item.text : '';
    },
    getAll(val, value) {
      // console.log(val, 'vallll-----');
      // console.log(value, 'valuelll-----');
      this.tableData = val;
      // if (this.setPerformExecuteFlag) {
      // }
    },

    // 预留
    hold() {
      if (!this.partFlag) {
        if (this.selectColumns.length <= 0) {
          this.$notify.warning({ title: '提示信息', message: '请选择要预留的配件！' });
          return;
        }
        this.$confirm('是否确定预留？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let obj = {
            obligatedNo: this.topFilterList.find(item => item.fieldName === 'obligatedNo').initialValue || '',
            applicant: this.topFilterList.find(item => item.fieldName === 'applicant').initialValue || '',
            owenNo: this.topFilterList.find(item => item.fieldName === 'ownerNo').initialValue || '',
            ownerName: this.topFilterList.find(item => item.fieldName === 'ownerName').initialValue || '',
            license: this.topFilterList.find(item => item.fieldName === 'license').initialValue || '',
            remark: this.topFilterList.find(item => item.fieldName === 'remark').initialValue || '',
            itemIds: this.itemIds || '',
            tables: this.tableData,
            // 模块区分
            ptype: this.ptype ? this.ptype : null
          };
          // console.log(obj, '----obj----');
          let a = (this.btnDisabled = true);
          this.columns.find(x => x.dataIndex === 'quantity').disabled = true;
          if (this.tableData.length == 0) {
            a = false;
            return this.$notify.warning({ title: '提示信息', message: '请添加需要预留的配件！' });
          }
          this.tableData.forEach(x => {
            // 增加预留数量判断
            if (x.quantity <= 0) {
              a = false;
              return this.$notify.warning({ title: '提示信息', message: '请输入预留数量！' });
            }
            if (Number(x.useableStock) < Number(x.quantity)) {
              a = false;
              return this.$notify.warning({ title: '提示信息', message: '预留数量不能大于可用库存！' });
            }
          });
          if (a) {
            this.getperformExecutes(obj);
          }
          // debugger;
        });
      }
    },

    async getperformExecutes(val) {
      const res = await performExecutes(val);
      this.obligatedNo = res.data.obligatedNo;
      if (res.resultCode === 200) {
        this.$notify.success({ title: '提示信息', message: '预留成功！' });
        this.topFilterList.find(item => item.fieldName === 'obligatedNo').initialValue = this.obligatedNo;

        let res = await queryPartObligatedItem({ obligatedNo: this.obligatedNo });
        this.dataSource = res.data.rows;
        this.topFilterList.find(item => item.fieldName === 'applicant').disabled = true;
        this.btn = this.btn1 = true;
        this.btn2 = false;
      }
    },

    // 解预留
    close(row) {
      // 查看当前用户是否有解预留权限
      if (isAuthorized('1313', '13131015')) {
        console.log(row, 'row');
        let ID = '';

        this.$confirm('是否确定解预留？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // this.row.forEach(x => {
          //   if (x.isObligated === 10041001) {
          //     ID = ID + ',' + x.itemId;
          //   }
          // });
          ID = row.itemId;
          let res = {
            obligatedNo: row.obligatedNo,
            applicant: row.applicant,
            owenNo: row.owenNo,
            ownerName: row.ownerName,
            license: row.license,
            remark: row.remark,
            itemIds: ID ? ID : '',
            tables: this.tableData
          };
          console.log(res, 'res');
          if (ID) {
            this.setPerformExecute(res);
          } else {
            this.$notify.success({ title: '提示信息', message: '没有解预留的配件！' });
          }
        });
      } else {
        this.$notify({
          title: '提示',
          message: '当前用户无解预留按钮权限',
          type: 'warning'
        });
      }
    },
    async setPerformExecute(res) {
      let resPerformExecute = await performExecute(res);

      // console.log(resPerformExecute, 'performExecute res----');
      if (resPerformExecute.resultCode === 200) {
        this.btn2 = true;
        this.$notify.success({ title: '提示信息', message: '解预留成功' });
        this.setPerformExecuteFlag = true;
        // console.log(this.dataSource, 'dataSource');
        // let res = await queryPartObligatedItem({ obligatedNo: this.obligatedNo });
        // this.dataSource = res.data.rows;
        this.fetchParams = Object.assign({}, val);
        // this.BaseTable.EXECUTE_DELETE(this.selectColumns);
        // this.searchDataToTable(this.topFilterList.find(item => item.fieldName === 'obligatedNo').initialValue);
      }
    },
    reset() {
      this.$refs.topFilter.RESET_FORM();
      this.BaseTable.EXECUTE_DELETE(this.tableData);
      this.btn = this.btn1 = this.btn2 = true;
      this.btn0 = false;
      this.yuliudan = false;
      for (let i = 0; i < this.topFilterList.length; i++) {
        this.topFilterList[i].readonly = false;
        if (i == 5 || i == 6 || i == 7 || i == 8) {
          this.topFilterList[i].disabled = true;
        } else {
          this.topFilterList[i].disabled = false;
        }
      }
    },
    toAddBtn() {
      this.btn = false;
      this.btn0 = true;
      this.yuliudan = true;
      for (let i = 0; i < this.topFilterList.length; i++) {
        this.topFilterList[i].readonly = false;
        if (i == 0 || i == 1) {
          this.topFilterList[i].disabled = true;
        } else {
          this.topFilterList[i].disabled = false;
        }
      }
      this.columns.find(x => x.dataIndex === 'quantity').disabled = false;
      this.topFilterList.find(item => item.fieldName === 'applicant').initialValue = +this.userId;
    },
    addHandle() {
      this.visible1 = true;
      this.handleType1 = 'add';
      this.btnDisabled = false;
      this.showHandler1();
    },
    delete(row) {
      this.handleType = 'edit';
      this.formData = row;
      this.$confirm('是否确定删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (row.itemId) {
          this.itemIds = this.itemIds + ',' + row.itemId;
        }
        this.$refs.table.EXECUTE_DELETE([row]);
        this.btn1 = false;
      });
    },
    changeHandle(val) {
      this.fetchParams = Object.assign({}, val);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    showHandler() {
      this.dialogTitle = `${this.conf[this.handleType]}品牌`;
      this.visible = true;
    },
    showHandler1() {
      this.dialogTitle1 = `新增预留`;
      this.visible1 = true;
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    closeHandler1(val, type) {
      this.visible1 = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams1 = { ...this.fetchParams };
      }
    },
    closeHandlergongdan(val, type) {},
    searchAll() {
      this.dialogTitle = '查询预留单';
      this.obligatedNo = this.topFilterList.find(x => x.fieldName === 'obligatedNo').initialValue;
      this.visible = true;
      this.handleType = 'add';
    },
    getData(str, flag) {
      this.chooseFlag = 2;
      let arr = flag[0];
      let param = '';
      for (let key in arr) {
        for (let i = 0; i < this.topFilterList.length; i++) {
          if (key == this.topFilterList[i].fieldName) this.topFilterList[i].initialValue = arr[key];
          if (key == 'obligatedNo') param = arr[key];
        }
      }
      this.searchDataToTable(param);
      this.btnDisabled = this.btn0 = this.btn1 = true;
      this.topFilterList.find(item => item.fieldName === 'applicant').initialValue = +arr.applicant;
      this.topFilterList.find(item => item.fieldName === 'obligatedNo').disabled = true;
      this.topFilterList.find(item => item.fieldName === 'applicant').disabled = true;
      this.topFilterList.find(item => item.fieldName === 'ownerName').disabled = true;
      this.topFilterList.find(item => item.fieldName === 'license').disabled = true;
      this.topFilterList.find(item => item.fieldName === 'remark').disabled = true;
      this.btn2 = false;
    },
    async searchDataToTable(arr) {
      let res = await queryPartObligatedItem({ obligatedNo: arr });
      this.BaseTable.EXECUTE_INSERT(res.data.rows);
    }
  }
};
</script>

<style lang="less" scoped></style>
